package com.ido.otaclient.four;


import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.text.TextUtils;
import android.util.Log;


import com.ido.otaclient.R;
import com.ido.otaclient.Status;
import com.ido.otaclient.StatusDownload;
import com.ido.otaclient.StatusUpgrade;
import com.ido.otaclient.api.OkhttpUtil;
import com.ido.otaclient.base.ApiConstant;
import com.ido.otaclient.base.Constant;
import com.ido.otaclient.base.IDLog;
import com.ido.otaclient.module.Veneer;
import com.ido.otaclient.util.AppExecutors;
import com.ido.otaclient.util.FileUtil;
import com.ido.otaclient.util.GZipUtil;
import com.ido.otaclient.util.ResourceUtil;
import com.koushikdutta.async.http.AsyncHttpClient;
import com.koushikdutta.async.http.AsyncHttpPost;
import com.koushikdutta.async.http.AsyncHttpResponse;
import com.koushikdutta.async.http.body.MultipartFormDataBody;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * Copyright (c) 2019 深圳市爱都科技有限公司. All rights reserved.
 *
 * @Author: xyb
 * @CreateDate: 2020-02-28 21:29
 * @description
 */
public class FourToOnePresenter implements FourToOneContract.Presenter{
    private FourToOneContract.View mView;

    private static final String TAG = "FourToOnePresenter";

    /**
     * bootloader 选择字库文件
     */
    private static final int REQUEST_CODE_B = 1000;
    /**
     * 选择特殊固件
     */
    private static final int REQUEST_CODE_SPECIAL = 1001;
    /**
     * 选择字库文件
     */
    private static final int REQUEST_CODE_FONT = 1002;
    /**
     * 选择最新固件
     */
    private static final int REQUEST_CODE_NEW = 1003;

    public FourToOnePresenter(FourToOneContract.View mView) {
        this.mView = mView;
    }

    @Override
    public void fileZip() {
        String filePathB = mView.getBootloaderFilePath();
        String fileVersionB = mView.getBootloaderVersion();
        String filePathSpecial = mView.getSpecialFilePath();
        String fileVersionSpecial = mView.getSpecialFileVersion();
        String filePathFont = mView.getFontFilePath();
        String fileFontVersion = mView.getFontFileVersion();
        String filePathNew = mView.getNewFilePath();
        String fileVersionNew = mView.getNewFileVersion();

        if(TextUtils.isEmpty(filePathB)){
            mView.showMessage(ResourceUtil.getString(R.string.please_choose_bootloader_file));
            return;
        }
        if(TextUtils.isEmpty(fileVersionB)){
            mView.showMessage(ResourceUtil.getString(R.string.please_input_bootloader_file_version));
            return;
        }
        if(TextUtils.isEmpty(filePathSpecial)){
            mView.showMessage(ResourceUtil.getString(R.string.please_choose_special_file));
            return;
        }
        if(TextUtils.isEmpty(fileVersionSpecial)){
            mView.showMessage(ResourceUtil.getString(R.string.please_input_special_file_version));
            return;
        }
        if(TextUtils.isEmpty(filePathFont)){
            mView.showMessage(ResourceUtil.getString(R.string.please_choose_font_file));
            return;
        }
        if(TextUtils.isEmpty(fileFontVersion)){
            mView.showMessage(ResourceUtil.getString(R.string.please_input_font_file_version));
            return;
        }
        if(TextUtils.isEmpty(filePathNew)){
            mView.showMessage(ResourceUtil.getString(R.string.please_choose_new_file));
            return;
        }
        if(TextUtils.isEmpty(fileVersionNew)){
            mView.showMessage(ResourceUtil.getString(R.string.please_input_new_file_version));
            return;
        }
        if(TextUtils.isEmpty(mView.getDeviceId())){
            mView.showMessage(ResourceUtil.getString(R.string.please_input_device_id));
            return;
        }
        /**
         * 拷贝文件同时获得拷贝之后文件的路径
         */
        mView.setPathFolderZip(copyFile());
        uploadAndConfirmFile();
    }

    @Override
    public void uploadAndConfirmFile() {
        String fileBName = mView.getBootloaderFileName();
        String fileSpecialName = mView.getSpecialFileName();
        String fileFontName = mView.getFontFileName();
        String fileNewName = mView.getNewFileName();
        String fileVersionB = mView.getBootloaderVersion();
        String fileVersionSpecial = mView.getSpecialFileVersion();
        String fileFontVersion = mView.getFontFileVersion();
        String fileVersionNew = mView.getNewFileVersion();

        if(TextUtils.isEmpty(mView.getPathFolderZip())){
            mView.showMessage(ResourceUtil.getString(R.string.file_zip_fail));
            return;
        }
        /**
         * 获得带有状态的单板列表
         */
        List<Veneer> veneerList = mView.getVeneerList();
        if(veneerList == null || veneerList.size() == 0){
            mView.showMessage(ResourceUtil.getString(R.string.veneer_not_found));
            return;
        }
        mView.showLoading();
        //判断是否需要下发固件
        for(Veneer veneer : veneerList){
            if(!TextUtils.isEmpty(veneer.getIp()) &&
                    veneer.getDownloadStatus() == StatusDownload.START.getCode()){
                /*Veneer veneer = new Veneer();
                veneer.setIp("192.168.1.5");*/
                String url = ApiConstant.URL_HEAD + veneer.getIpPort();
                mView.setIsComplete(false);
                uploadFile(url,veneer.getIpPort(),mView.getPathFolderZip(),fileBName,fileVersionB,
                        fileSpecialName,fileVersionSpecial,fileFontName,fileFontVersion,
                        fileNewName,fileVersionNew);

                break;
            }
        }
        if(mView.getIsComplete()){
            mView.hideLoading();
            saveUploadType();
        }
    }

    @Override
    public void chooseFile(int requestCode,Activity activity) {
        Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
        intent.addCategory(Intent.CATEGORY_OPENABLE);
        String fileFolder = Constant.DIR_OUT_SDCRA;
        File file = new File(fileFolder);
        if (file.exists()) {
            //从指定目录下选择文件 这个现在不知道能不能实现 现在还是查询所有目录下的
            Uri uri = FileUtil.getUriFromFile(activity, fileFolder);
            //Log.d(TAG, fileFolder + "," + uri.getPath());
            //intent.setDataAndType(uri, "*/*");
            intent.setType("*/*");
        } else {
            intent.setType("*/*");
        }
        activity.startActivityForResult(intent, requestCode);
    }

    @Override
    public void onActivityResult(Activity act, int requestCode, int resultCode, Intent data) {
        if (data == null) {
            // 用户未选择任何文件，直接返回
            return;
        }
        String path = "";
        Uri uri = data.getData(); // 获取用户选择文件的URI
        if ("file".equalsIgnoreCase(uri.getScheme())) {//使用第三方应用打开
            path = uri.getPath();
        } else {
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {//4.4以后
                path = FileUtil.getPath(act, uri);
            } else {//4.4以下下系统调用方法
                //path = FileUtil.getRealPathFromURI(this, uri);
            }
        }
        switch (requestCode) {
            case REQUEST_CODE_B:
                mView.setIvChooseBootloader();
                if (!TextUtils.isEmpty(path)) {
                    mView.showBootloaderName(true);
                    mView.setBootloaderFilePath(path);
                    mView.setBootloaderFileName(FileUtil.getFileNameFromPath(path));
                }

                break;
            case REQUEST_CODE_SPECIAL:
                mView.setIvChooseSpecial();
                if (!TextUtils.isEmpty(path)) {
                    mView.showSpecialName(true);
                    mView.setSpecialFilePath(path);
                    mView.setSpecialFileName(FileUtil.getFileNameFromPath(path));
                }
                break;
            case REQUEST_CODE_FONT:
                mView.setIvChooseFont();
                if (!TextUtils.isEmpty(path)) {
                    mView.showFontName(true);
                    mView.setFontFilePath(path);
                    mView.setFontFileName(FileUtil.getFileNameFromPath(path));
                }
                break;
            case REQUEST_CODE_NEW:
                mView.setIvChooseNew();
                if (!TextUtils.isEmpty(path)) {
                    mView.showNewName(true);
                    mView.setNewFilePath(path);
                    mView.setNewFileName(FileUtil.getFileNameFromPath(path));
                }
                break;
            default:
                break;
        }
    }

    @Override
    public void initConfig() {
        FourToOnePreference fourToOnePreference = FourToOnePreference.getInstance();
        FourToOneConfig fourToOneConfig = fourToOnePreference.getUploadConfig();
        if(fourToOneConfig != null ){
            if(TextUtils.isEmpty(fourToOneConfig.getBootloaderName())){
                mView.showBootloaderName(false);
            }else {
                mView.setIvChooseBootloader();
                mView.showBootloaderName(true);
            }
            if(TextUtils.isEmpty(fourToOneConfig.getFirewareSpecialName())){
                mView.showSpecialName(false);
            }else {
                mView.setIvChooseSpecial();
                mView.showSpecialName(true);
            }
            if(TextUtils.isEmpty(fourToOneConfig.getFontName())){
                mView.showFontName(false);
            }else {
                mView.setIvChooseFont();
                mView.showFontName(true);
            }
            if(TextUtils.isEmpty(fourToOneConfig.getFirewareNewName())){
                mView.showNewName(false);
            }else {
                mView.setIvChooseNew();
                mView.showNewName(true);
            }

            mView.setBootloaderFilePath(fourToOneConfig.getBootloaderPath());
            mView.setBootloaderFileName(fourToOneConfig.getBootloaderName());
            mView.setBootloaderVersion(fourToOneConfig.getBootloaderVersion());

            mView.setSpecialFilePath(fourToOneConfig.getFirewareSpecialPath());
            mView.setSpecialFileName(fourToOneConfig.getFirewareSpecialName());
            mView.setSpecialVersion(fourToOneConfig.getFirewareSpecialVersion());

            mView.setFontFilePath(fourToOneConfig.getFontPath());
            mView.setFontFileName(fourToOneConfig.getFontName());
            mView.setFontVersion(fourToOneConfig.getFontVersion());

            mView.setNewFilePath(fourToOneConfig.getFirewareNewPath());
            mView.setNewFileName(fourToOneConfig.getFirewareNewName());
            mView.setNewVersion(fourToOneConfig.getFirewareNewVersion());

            mView.setDeviceId(fourToOneConfig.getDeviceId());

        }

    }

    @Override
    public void start() {

    }

    @Override
    public void release() {

    }

    /**
     * 上传文件
     * @param url
     * @param filePath
     */
    private void uploadFile(String url,String ipPort, String filePath,String fileBName,String fileVersionB,
                            String fileSpecialName,String fileVersionSpecial,String fileFontName,
                            String fileFontVersion, String fileNewName,String fileVersionNew) {
        long size = FileUtil.getFileSize(filePath);
        String sizeStr = String.valueOf(size);

        AsyncHttpPost post = new AsyncHttpPost(url + "/upload");
        MultipartFormDataBody body = new MultipartFormDataBody();
        body.addFilePart("text.zip", new File(filePath));
        // 文件名传递
        body.addStringPart("foo", "upload.zip");
        post.setBody(body);
        AsyncHttpClient.getDefaultInstance().executeString(post, new AsyncHttpClient.StringCallback() {
            @Override
            public void onCompleted(Exception ex, AsyncHttpResponse source, String result) {
                if (ex != null) {
                    AppExecutors.globalAppExecutors().mainThread().execute(() -> updateVeneer(ipPort));
                    ex.printStackTrace();
                    return;
                }
                mView.setIsComplete(true);
                //确认成功
                confirmUploadFile(url,ipPort,sizeStr,fileBName,fileVersionB,
                        fileSpecialName,fileVersionSpecial,fileFontName,fileFontVersion,
                        fileNewName,fileVersionNew);
            }
        });
    }

    /**
     * 文件上传失败更新单板信息
     * @param ipPort 请求的ip + 端口号
     */
    private void updateVeneer(String ipPort) {
        List<Veneer> veneerList = new ArrayList<>();
        veneerList.addAll(mView.getVeneerList());
        for(int i= 0;i < veneerList.size();i++){
            Veneer veneer = veneerList.get(i);
            if(ipPort.equals(veneer.getIpPort())){
                //veneer.setDownloadStatus(StatusDownload.COMPLETE.getCode());
                int failCount = veneer.getFailConnectCount();
                veneer.setFailConnectCount(++failCount);
                veneer.setDownloadStatus(StatusDownload.START.getCode());
                if(failCount >= 3){
                    veneer.setUpdateStatus(StatusUpgrade.FAIL.getCode());
                }
                veneerList.set(i,veneer);
                mView.setVeneerList(veneerList);
            }
        }
        mView.showConfirmCancel();
    }

    /**
     * 文件确认
     * @param url
     * @param sizeStr
     */
    private void confirmUploadFile(String url,String ipPort,String sizeStr,String fileBName,String fileVersionB,
                                   String fileSpecialName,String fileVersionSpecial,String fileFontName,
                                   String fileFontVersion, String fileNewName,String fileVersionNew) {
        StringBuffer sb = new StringBuffer();
        sb.append(url);
        sb.append("/");
        sb.append(ApiConstant.METHOD_CONFIRM_FIREWARE);
        sb.append("?");
        sb.append("size=");
        sb.append(sizeStr);
        sb.append("&");
        sb.append("taskType=");
        sb.append(Constant.TASK_NAME_FOUR_TO_ONE);
        sb.append("&");
        sb.append("bootloaderName=");
        sb.append(fileBName);
        sb.append("&");
        sb.append("bootloaderVersion=");
        sb.append(fileVersionB);
        sb.append("&");
        sb.append("firewareSpecialName=");
        sb.append(fileSpecialName);
        sb.append("&");
        sb.append("firewareSpecialVersion=");
        sb.append(fileVersionSpecial);
        sb.append("&");
        sb.append("fontName=");
        sb.append(fileFontName);
        sb.append("&");
        sb.append("fontVersion=");
        sb.append(fileFontVersion);
        sb.append("&");
        sb.append("firewareNewName=");
        sb.append(fileNewName);
        sb.append("&");
        sb.append("firewareNewVerion=");
        sb.append(fileVersionNew);
        sb.append("&");
        sb.append("deviceId=");
        sb.append(mView.getDeviceId());
        url = sb.toString();
        OkhttpUtil okhttpUtil = OkhttpUtil.getInstance();
        okhttpUtil.getSyn(url, new OkhttpUtil.OkhttpCallback() {
            @Override
            public void onSuccess(String success) {
                AppExecutors.globalAppExecutors().mainThread().execute(() -> updateVeneer(success,ipPort));
            }

            @Override
            public void onFailed(String message) {
                //mTvtest.setText(message);
                Log.d(TAG,message );
                AppExecutors.globalAppExecutors().mainThread().execute(() -> mView.showConfirmCancel());
            }
        });
    }

    /**
     * 更新单板下发文件状态下发下一个单板
     * @param success
     * @param ipPort ip + 端口号
     */
    private void updateVeneer(String success, String ipPort) {
        try {
            JSONObject jsonObject = new JSONObject(success);
            String errCode = jsonObject.getString("errcode");
            String errMsg = jsonObject.getString("errmsg");
            if(Integer.parseInt(errCode) == Status.REQUEST_OK.getRequestStatus()){
                List<Veneer> veneerList = new ArrayList<>();
                veneerList.addAll(mView.getVeneerList());
                for(int i= 0;i < veneerList.size();i++){
                    Veneer veneer = veneerList.get(i);
                    if(ipPort.equals(veneer.getIpPort())){
                        veneer.setDownloadStatus(StatusDownload.COMPLETE.getCode());
                        veneerList.set(i,veneer);
                        mView.setVeneerList(veneerList);
                        uploadAndConfirmFile();
                    }
                }
            }else {
                mView.showConfirmCancel();
            }
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    /**
     * 拷贝文件
     */
    private String copyFile() {
        String fileBName = mView.getBootloaderFileName();
        String fileSpecialName = mView.getSpecialFileName();
        String fileFontName = mView.getFontFileName();
        String fileNewName = mView.getNewFileName();

        //1、将所有的zip文件移动到一个文件夹中2、压缩文件3、上传给服务器器
        String pathTo = Constant.DIR_IN_SDCARD_UPLOAD;
        IDLog.d(TAG, "copyFile: " + pathTo);
        File fileFolder = new File(pathTo);
        if(fileFolder.exists()){
            FileUtil.deleteDirectory(pathTo);
            fileFolder.mkdirs();
        }else {
            fileFolder.mkdirs();
        }
        try {
            FileUtil.copyFile(mView.getBootloaderFilePath(),
                    pathTo + File.separator+ fileBName,false);
            FileUtil.copyFile(mView.getSpecialFilePath(),
                    pathTo + File.separator + fileSpecialName,false);
            FileUtil.copyFile(mView.getFontFilePath(),
                    pathTo + File.separator + fileFontName,false);
            FileUtil.copyFile(mView.getNewFilePath(),
                    pathTo + File.separator + fileNewName,false);
        } catch (IOException e) {
            e.printStackTrace();
        }

        String pathFolderZip = Constant.DIR_IN_SDCARD_UPLOAD_zip;
        IDLog.d(TAG, "copyFile: " +pathFolderZip);
        File fileZip = new File(pathTo);
        if(fileZip.exists()){
            fileZip.delete();
            fileZip.mkdir();
        }
        try {
            //压缩文件
            GZipUtil.ZipFolder(pathTo,pathFolderZip);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return pathFolderZip;
    }

    /**
     * 保存
     */
    private void saveUploadType() {
        FourToOnePreference fourToOnePreference = FourToOnePreference.getInstance();
        String fileNameBoot = mView.getBootloaderFileName();
        String fileVersionBoot = mView.getBootloaderVersion();
        String fileNameSpecial = mView.getSpecialFileName();
        String fileVersionSpecial = mView.getSpecialFileVersion();
        String fileFontName = mView.getFontFileName();
        String fileVersionFont = mView.getFontFileVersion();
        String fileNewName = mView.getNewFileName();
        String fileNewVersion = mView.getNewFileVersion();

        FourToOneConfig fourToOneConfig = new FourToOneConfig();
        fourToOneConfig.setTaskName(Constant.TASK_NAME_FOUR_TO_ONE);
        fourToOneConfig.setBootloaderName(fileNameBoot);
        fourToOneConfig.setBootloaderVersion(fileVersionBoot);
        fourToOneConfig.setFirewareSpecialName(fileNameSpecial);
        fourToOneConfig.setFirewareSpecialVersion(fileVersionSpecial);
        fourToOneConfig.setFontName(fileFontName);
        fourToOneConfig.setFontVersion(fileVersionFont);
        fourToOneConfig.setFirewareNewName(fileNewName);
        fourToOneConfig.setFirewareNewVersion(fileNewVersion);
        fourToOneConfig.setFirewareSpecialPath(mView.getSpecialFilePath());
        fourToOneConfig.setFirewareNewPath(mView.getNewFilePath());
        fourToOneConfig.setBootloaderPath(mView.getBootloaderFilePath());
        fourToOneConfig.setFontPath(mView.getFontFilePath());
        fourToOneConfig.setDeviceId(mView.getDeviceId());
        fourToOnePreference.saveUploadConfig(fourToOneConfig);

        mView.showMessage(ResourceUtil.getString(R.string.upload_file_success));
        mView.back();

    }
}
